/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ola_network.h"
#include <string.h>
#include "ola_pal_network.h"
#include "ola_log.h"
#include "ola_def.h"
#include "ola_error.h"
#include "ola_pal_os.h"
#include "ola_base_utils.h"

#define NETWORK_WAIT_INTERVAL   1000
#define NETWORK_WAIT_OVERTIME   (60 * 1000)

static bool g_waitFlag = false;

bool OlaIsNetworkConnected(void)
{
    int state = 0;
    int ret = OlaGetNetworkState(&state);
    if (ret != 0) {
        OlaLogError("get network state error[%d]", ret);
        return false;
    }

    char ip[OLA_IP_LEN + 1] = {0};
    ret = OlaGetIpAddr(ip, OLA_IP_LEN);
    if (ret != 0) {
        OlaLogError("get network state error[%d]", ret);
        return false;
    }

    if ((strlen(ip) != 0) && (strcmp(ip, OLA_INVALID_IP) != 0)) {
        return true;
    }

    return false;
}

int OlaWaitNetworkConnected(void)
{
    int ret;
    if (!OlaIsNetworkConnected()) {
        ret = OlaConnectWifi();
        if (ret != 0) {
            OlaLogError("trigger wifi connect error[%d]", ret);
            return OLA_NETWORK_ERR_CONNECT_WIFI;
        }
    }

    g_waitFlag = true;
    bool isOvertime = false;
    bool isConnect = false;
    unsigned long  long startTime = 0;
    if (OlaGetTime(&startTime) != OLA_OK) {
        OlaLogError("get time failed");
        return OLA_OS_ERR_GET_TIME;
    }

    do {
        OlaLogInfo("Waitting network connected...");
        isConnect = OlaIsNetworkConnected();
        if (!isConnect) {
            ret = OlaIsOvertime(&isOvertime, startTime, NETWORK_WAIT_OVERTIME);
            if (ret != OLA_OK) {
                OlaLogError("check overtime failed");
                return ret;
            }
            if (!isOvertime) {
                OlaSleepMs(NETWORK_WAIT_INTERVAL);
            }
        } else {
            OlaLogNotice("network connected");
            return OLA_OK;
        }
    } while (g_waitFlag && !isConnect && !isOvertime);

    return OLA_NETWORK_ERR_NOT_CONNECT;
}

void OlaWaitNetworkConnectedExit(void)
{
    g_waitFlag = false;
}

